
<script setup>
import { onMounted, ref } from 'vue'
import axios from 'axios'
import bwPowerSet from '@/utils/power-set.js'
import { ElMessage } from 'element-plus'
// 商品规格数据
const goods = ref({})

// 路径字典对象
let pathMap = {}

// 选定的商品sku
const selectedSku = ref({})

// 获取商品规格数据
const getGoods = async () => {
  // 1135076  初始化就有无库存的规格
  // 1369155859933827074 更新之后有无库存项（蓝色-20cm-中国）
  const res = await axios.get('http://pcapi-xiaotuxian-front-devtest.itheima.net/goods?id=1369155859933827074')
  goods.value = res.data.result
  goods.value.specs.forEach(item => {
    item.values.forEach(val => {
        val.isSelected = false
    })
  })
//   sku路径字典对象
  pathMap = getPathMap(goods.value)

//   初始化禁用状态
  initDisabled(goods.value.specs,pathMap)

  // changeDisabled(goods.value.specs,pathMap.value)
}

// 切换激活状态
const changeActive = (item,val) => {
    if(val.disabled) return
    if(val.isSelected)  {
    // 当前项已激活
        val.isSelected = false
    } else {
        // 当前未激活
        item.values.forEach(i => {
        i.isSelected = false
    })
    val.isSelected = true
    }

    changeDisabled(goods.value.specs,pathMap)
    const index = getSelectedVal(goods.value.specs).findIndex(item => item === undefined)
    if(index > -1) {
        ElMessage.warning('请选择完整规格')
    } else {
        // alert('没找到')
        const key = getSelectedVal(goods.value.specs).join('-')
        // console.log(key);

        // 匹配选中的skuid
        const skuIds = pathMap[key] 
        
        // 查找当前选中的sku
       const skuObj =  goods.value.skus.find(item => item.id === skuIds[0])
        // console.log(skuObj);
        selectedSku.value = skuObj
    }

}

// 生成有效sku字典路径
const getPathMap = (goods) => {

    const pathMap = {}

    // 1.根据sku生成有效的sku数组-通过数据库存数量筛选过滤，保留库存不为零的商品数据
    const effectiveSku = goods.skus.filter(sku => sku.inventory > 0)

    // 2.根据有效的sku通过子集算法生成有效sku字典路径-[1,2] -> [[1],[2],[1,2]]
    effectiveSku.forEach(sku => {
        // 2.1获取用于匹配的sku属性值数组
        const selectedValArr = sku.specs.map(item => item.valueName)

        // 2.2使用算法获取子集
        const valueArrPowerSet = bwPowerSet(selectedValArr)

        // 3.将得到的自己生成路径字典对象
        valueArrPowerSet.forEach(item => {
            // 初始化key
            const key = item.join('-')
            // 如果已经存在key，则直接添加skuid
            if(pathMap[key]) {
                pathMap[key].push(sku.id)
            } else {
                // 如果不存在key，则初始化
                pathMap[key] = [sku.id]
            }
        })
    })
    return pathMap
}

// 初始化禁用状态
const initDisabled = (specs, pathMap) => {
    specs.forEach(spec => {
        spec.values.forEach(item => {
        if (pathMap[item.name]) {
            item.disabled = false
        } else {
            item.disabled = true
        }
    })
    })
}

// 获取选中的规格属性值
const getSelectedVal = (specs) => {
    const arr  =[]
    specs.forEach(item => {
        arr.push(item.values.find(item => item.isSelected)?.name)
    })
    return arr

}

// 切换时更新禁用状态
const changeDisabled = (specs, pathMap) => {


    // 遍历所有规格属性值
    specs.forEach((item, index) => {
    // 获取选中属性值
    const selectedVal = getSelectedVal(specs)

        item.values.forEach(val => {
            // console.log(val.name);
            selectedVal[index] = val.name
            const key = selectedVal.filter(item => item).join('-')
            // console.log(key);
            if (pathMap[key]) {
                val.disabled = false
            } else {
                val.disabled = true
            }
        })
 
    })
}

// 判断用户是否选择的所有规格
const isAllSelected = (specs) => {
    
}
onMounted(() => getGoods())

</script>

<template>
  <div class="goods-sku">
    <dl v-for="item in goods.specs" :key="item.id">
      <dt>{{ item.name }}</dt>
      <dd>
        <template v-for="val in item.values" :key="val.name" >
          <!-- 图片类型规格 -->
          <img  @click="changeActive(item,val)" v-if="val.picture" :src="val.picture" :title="val.name" :class="{ selected: val.isSelected, disabled: val.disabled }" >
          <!-- 文字类型规格 -->
          <span @click="changeActive(item,val)" v-else :class="{ selected: val.isSelected, disabled: val.disabled  }">{{ val.name }}</span>
        </template>
      </dd>
    </dl>
  </div>
</template>

<style scoped lang="scss">
@mixin sku-state-mixin {
  border: 1px solid #e4e4e4;
  margin-right: 10px;
  cursor: pointer;

  &.selected {
    border-color: #27ba9b;
  }

  &.disabled {
    opacity: 0.6;
    border-style: dashed;
    cursor: not-allowed;
  }
}

.goods-sku {
  padding-left: 10px;
  padding-top: 20px;

  dl {
    display: flex;
    padding-bottom: 20px;
    align-items: center;

    dt {
      width: 50px;
      color: #999;
    }

    dd {
      flex: 1;
      color: #666;

      >img {
        width: 50px;
        height: 50px;
        margin-bottom: 4px;
        @include sku-state-mixin;
      }

      >span {
        display: inline-block;
        height: 30px;
        line-height: 28px;
        padding: 0 20px;
        margin-bottom: 4px;
        @include sku-state-mixin;
      }
    }
  }
}
</style>